package com.atgm.mall.gmmallauth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atgm.common.constant.AuthConstant;
import com.atgm.common.exception.BizCodeEnume;
import com.atgm.common.utils.GmMallUtils;
import com.atgm.common.utils.JwtUtils;
import com.atgm.common.utils.R;
import com.atgm.common.vo.MemberResponseVo;
import com.atgm.mall.gmmallauth.feign.MemberFeignService;
import com.atgm.mall.gmmallauth.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/gmmallauth")
@RestController
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Resource
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        //防刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.SMS_CODE + phone);
        if (GmMallUtils.isNotEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(10005, "发送频繁");
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthConstant.SMS_CODE + phone, code, 10, TimeUnit.MINUTES);

        return R.ok();
    }

    @PostMapping("/login")
    public R login(@RequestBody UserLoginVo vo) {
        //远程登录
        R login = memberFeignService.login(vo);
        MemberResponseVo data = null;
        if (login.getCode() == 0) {
            data = login.getData(new TypeReference<MemberResponseVo>() {});
            //存储redis
            Long id = data.getId();
            String username = data.getUsername();
            String token = JwtUtils.generateToken(id, username);
            //存储token
            stringRedisTemplate.opsForValue().set(AuthConstant.LOGIN_USER + id, token, 1L, TimeUnit.DAYS);
            data.setToken(token);
        } else {
            return R.error(BizCodeEnume.USER_LOGIN.getCode(), "登录失败");
        }
        return R.ok().setData(data);
    }

    @GetMapping("/logout")
    public R logout(@RequestParam String token) {
        log.info("token : {}", token);
        //从token中获取用户名
        Long memberId = JwtUtils.getMemberId(token);
        Boolean delete = stringRedisTemplate.delete(AuthConstant.LOGIN_USER + memberId);
        if (!delete) {
            return R.error(BizCodeEnume.USER_LOGOUT.getCode(), BizCodeEnume.USER_LOGOUT.getMsg());
        }
        return R.ok();
    }
}
